package com.java.service.impl.center;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.enums.YseOrNo;
import com.java.common.utils.PageUtils;
import com.java.mapper.ItemsCommentsDao;
import com.java.pojo.ItemsComments;
import com.java.pojo.OrderItems;
import com.java.pojo.OrderStatus;
import com.java.pojo.Orders;
import com.java.pojo.bo.center.OrderItemsCommentBO;
import com.java.pojo.vo.MyCommentVO;
import com.java.service.OrderItemsService;
import com.java.service.OrderStatusService;
import com.java.service.OrdersService;
import com.java.service.center.MyCommentsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service("myCommentsService")
public class MyCommentsServiceImpl extends ServiceImpl<ItemsCommentsDao, ItemsComments> implements MyCommentsService {
    @Autowired
    private OrderItemsService orderItemsService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderStatusService orderStatusService;

    @Override
    public List<OrderItems> queryPendingComment(String orderId) {
        return orderItemsService.list(new LambdaQueryWrapper<OrderItems>().eq(OrderItems::getOrderId,orderId));
    }

    @Override
    @Transactional
    public void saveComments(String orderId, String userId, List<OrderItemsCommentBO> commentList) {
        // 1. 保存评价 items_comments
        List<ItemsComments> comments = commentList.stream().map(e -> {
            ItemsComments itemsComments = new ItemsComments();
            BeanUtils.copyProperties(e, itemsComments);
            itemsComments.setId(String.valueOf(IdWorker.getId()));
            itemsComments.setUserId(userId);
            return itemsComments;
        }).collect(Collectors.toList());
        saveBatch(comments);

        // 2. 修改订单表改已评价 orders
        Orders order = new Orders();
        order.setId(orderId);
        order.setIsComment(YseOrNo.YES.code);
        ordersService.updateById(order);

        // 3. 修改订单状态表的留言时间 order_status
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setCommentTime(new Date());
        orderStatusService.updateById(orderStatus);
    }

    @Override
    public PageUtils queryMyComments(String userId, Integer page, Integer pageSize) {
        Page<MyCommentVO> pageOf = new Page<>(page,pageSize);
        List<MyCommentVO> list = this.baseMapper.queryMyComments(pageOf,userId);
        pageOf.setRecords(list);
        return new PageUtils(pageOf);
    }

}